<template>
	<view class="district" v-if="pagedList.length > 0">
		<swiper class="swiper" @change="swiperChange">
			<swiper-item class="list u-flex u-flex-wrap u-col-start" v-for="(page, pageIndex) in pagedList"
				:key="pageIndex">
				<view class="li u-flex u-flex-col u-flex-center" v-for="(val, k) in page" :key="k"
					@click="categorySwitchTab(val)">
					<view class="li-base u-flex-center">
						<image :src="val.image || ''" mode="widthFix" class="image"></image>
					</view>
					<view class="li-text">{{val.name}}</view>
				</view>
			</swiper-item>
		</swiper>
		<view class="scroll" :style="{ width: scrollWidth }">
			<view class="scroll-active" :style="{ transform: `translateX(${activeDotOffset}px)` }"></view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				pagedList: [],
				activeDotOffset: 0,
			};
		},
		watch: {
			productCategoryList: {
				handler(newVal) {
					this.splitList(newVal);
				},
				immediate: true
			}
		},
		computed: {
			scrollWidth() {
				return `${this.pagedList.length * 19}px`;
			},
			...mapState({
				productCategoryList: (state) => state.index.productCategoryList
			})
		},
		methods: {
			splitList(list) {
				const itemsPerPage = 10;
				let result = [];
				for (let i = 0; i < list.length; i += itemsPerPage) {
					result.push(list.slice(i, i + itemsPerPage));
				}
				this.pagedList = result;
			},
			swiperChange({ detail: { current } }) {
				// 计算滚动条位置
				const scrollWidth = parseInt(this.scrollWidth, 10);
				const maxOffset = scrollWidth - 19; // 19是滚动指示器的宽度
				const activeDotOffset = (current / (this.pagedList.length - 1)) * maxOffset;
				this.activeDotOffset = activeDotOffset;
			},
			categorySwitchTab(e) {
				if (e.mod_type == 2) {
					this.$navigateTo('/apparatusSubPackages/index/index?tabbarIndex=1&id=' + e.id);
				} else {
					this.$switchTab('/pages/category/index')
					this.$store.commit("init/setCategory", e.id)
				}
			}
		}
	};
</script>

<style lang="scss">
	.district {
		.swiper {
			min-width: 100%;
			height: 400rpx;

			.list {
				padding-top: 20rpx;

				.li {
					width: 20%;
					margin-top: 20rpx;

					.li-text {
						padding-top: 12rpx;
						font-size: 24rpx;
						color: #202020;
					}

					.image {
						width: 108rpx;
						height: 100%;
						display: block;
					}
				}
			}
		}

		.scroll {
			height: 4rpx;
			background-color: #EEEEEE;
			border-radius: 2rpx;
			margin: 10rpx auto 6rpx;

			.scroll-active {
				width: 19px;
				height: 4rpx;
				background: #888888;
				border-radius: 2rpx;
				transition: transform 0.1s;
			}
		}
	}
</style>